package com.dckj.auto.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dckj.auto.common.utils.DateUtils;
import com.dckj.auto.common.utils.StringUtil;
import com.dckj.auto.entity.AuthMenuRole;
import com.dckj.auto.entity.AuthRole;
import com.dckj.auto.dao.AuthRoleDao;
import com.dckj.auto.entity.AuthUserRole;
import com.dckj.auto.service.AuthMenuRoleService;
import com.dckj.auto.service.AuthRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dckj.auto.service.AuthUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WangDong123
 * @since 2018-09-03
 */
@Service
public class AuthRoleServiceImpl extends ServiceImpl<AuthRoleDao, AuthRole> implements AuthRoleService {
    @Autowired
    AuthRoleDao roleDao;
    @Autowired
    AuthMenuRoleService menuRoleService;
    @Autowired
    AuthUserRoleService userRoleService;

    @Override
    public Integer saveOrUpdate(AuthRole role) {
        if(StringUtils.isEmpty(role.getId())){
            role.setId(StringUtil.getUUId());
            role.setTime(DateUtils.getCurrentTime());
            role.setState(1);
            return roleDao.insert(role);
        }
        return roleDao.updateById(role);
    }

    @Override
    public Integer delete(String id) {
        Integer integer = roleDao.deleteById(id);
        if(integer>0){
            //删除关联表信息
            menuRoleService.delete(new EntityWrapper<AuthMenuRole>().eq("role_id",id));
            userRoleService.delete(new EntityWrapper<AuthUserRole>().eq("role_id",id));
        }
        return integer;
    }

    @Override
    public List<AuthRole> list(Page<AuthRole> page, String name) {
        EntityWrapper<AuthRole> en = new EntityWrapper<>();
        en.like(StringUtils.isNotEmpty(name),"name",name);
        en.orderBy("time",false);
       if(null == page){
           return roleDao.selectList(en);
       }
        return roleDao.selectPage(page,en);
    }

    @Override
    public Integer updateState(String id, Integer state) {
        AuthRole role = new AuthRole();
        role.setId(id);
        role.setState(state);
        return roleDao.updateById(role);
    }
}
